public  without sharing class AdjustPriceListController {

	public String prId{get;private set;}//价格调整的Id 
	public String dataJson {get;set;}

	public String accountType {get;set;}

	public Boolean isErr {get;set;}
    public Boolean isGPO { get;private set;}//是否是gpo客户
    public String rightString {get;private set;}
    public Map<String,Boolean> rightMap ;
    private String province ; 



    public AdjustPriceListController() {

        prId = System.currentPageReference().getParameters().get('id');
        dataJson = '[]';

        try {

            List<ProductBean> tmp = new List<ProductBean>();
            if(prId == null ) throw new DmlException('页面打开错误!');
            rightMap = getPriceFieldsMap();
            rightString = JSON.serialize(rightMap);
            if(Id.valueOf(prId).getSobjectType() == AdjustPrice__c.SObjecttype ){
                AdjustPrice__c ap = [select Id,Company__c,OwnerId , Account__r.Parent.AccountNumber,  Account__r.RecordType.DeveloperName,Account__r.System__c  from AdjustPrice__c where Id=:prId ];

                 accountType = ap.Account__r.System__c != null ? 'third' :  ap.Account__r.RecordType.DeveloperName == 'TerminalCustomer' ?   'terminal'   : 'dealer' ;
                 province = [select PriceProvince__c from User where Id=:ap.OwnerId ].PriceProvince__c;
                 tmp = getList(ap,accountType);
                 isGPO = ap.Account__r.Parent.AccountNumber == '301133';
                 

            }else if(Id.valueOf(prId).getSobjectType() == Quote.SObjecttype){

                Quote q = [select Id,Opportunity.Owner.PriceProvince__c,Opportunity.OwnerId,Opportunity.Account.Parent.AccountNumber ,ApplicableCustomers__c,Opportunity.AccountId ,Opportunity.Account.RecordType.DeveloperName,
                Opportunity.Owner.SubCompany__c,
                Opportunity.Account.System__c ,Opportunity.Account.ParentId  from Quote where Id=: prId];
                 accountType =  q.Opportunity.Account.System__c != null ?  'third' : q.Opportunity.Account.RecordType.DeveloperName == 'TerminalCustomer' ?  'terminal' : 'dealer' ;
                 isGPO = q.Opportunity.Account.Parent.AccountNumber == '301133';
                   province = q.Opportunity.Owner.PriceProvince__c;
                 tmp = getQuoteList(q,accountType);
               
            }else{
                 throw new DmlException('页面打开错误!');
            }
  
            System.debug(tmp);
             dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

        }
        catch (Exception e) {
            isErr = true;
            ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
        }
        

    }

    

    private Map<String,Boolean>  getPriceFieldsMap(){
        
        User u = [select Id,Name,Profile.Name from User where Id=:UserInfo.getUserId()];

        Map<String,Boolean> rightMap = new Map<String,Boolean>();
        for(String line : Label.PriceDetailRight.split(';')){

            if(!String.isBlank(line)){
                
                List<String> kvs = line.split('-');
             //   if(kvs.size() < 2)continue;
                if(kvs[0].trim().contains('|')){

                    for(String key :kvs[0].trim().split('\\|') ){
                        rightMap.put(key,(kvs[1].contains(u.Name) || kvs[1].contains(u.Profile.Name)));
                    }

                    
                }else{
                    rightMap.put(kvs[0].trim(),(kvs[1].contains(u.Name) || kvs[1].contains(u.Profile.Name)));
                }  
                


            }
        }

        
        System.debug(rightMap);
        return rightMap;

        

    }
    //获取调价明细
    public List<ProductBean>  getList( AdjustPrice__c ap,String type  ){
    	
        String company = ap.Company__c ;
     
    	List<ProductBean> tmp = new List<ProductBean>();
        List<AdjustPriceProduct__c> apList = [select Id,Product__c ,Product__r.Name,Product__r.ProductName__c ,Product__r.SerialNo__c,Product__r.Brand__c,QuotoReason__c,Product__r.Model__c,
            Product__r.Spec__c,AdjustSalesPrice__c,OriginalPrice__c,InvoiceDealerPrice__c,AreaDealerPrice__c,GPOPrice__c,Product__r.Category1__c,
            CompanyBottomPrice__c,LastMonthAveragePrice__c,HospitalManagerPrice__c,InstCost__c,SystemPrice__c,Product__r.swjhdj__c,Product__r.GroupSubCompanyPrice__c,
            Product__r.GroupDeclarationDealerPrice__c,Product__r.GroupRegionalDistributorsPrice__c,Product__r.GroupTerminalGuidePric__c 
            from AdjustPriceProduct__c where AdjustPrice__c =:ap.Id ];
         Set<Id>  pset= new Set<Id>();

        Set<Id> maccuras = new Set<Id>();
    	for(AdjustPriceProduct__c app:apList){
    		pset.add(app.Product__c );
    		if(MaccuraBrandUtil.maccura.contains(app.Product__r.Brand__c))maccuras.add(app.Product__c);

    	}
        Map<Id,Price__c> prMap = ImportObject.getPriceMap(pset, company,province);
        Map<Id,Price__c> maccuraPrMap = type != 'third'|| maccuras.isEmpty() ? new  Map<Id,Price__c>():   ImportObject.getPriceMap(maccuras, '迈克生物股份有限公司',false);
        System.debug('AdjustPriceListController==>'+prMap);
        for(AdjustPriceProduct__c app:apList){
            tmp.add(new ProductBean(app, maccuraPrMap.containsKey(app.Product__c) ? maccuraPrMap.get(app.Product__c) :  prMap.get(app.Product__c),rightMap,type == 'third'));
        }
        return tmp;

    }
   
    //获取报价明细
    public List<ProductBean>  getQuoteList(Quote q ,String type ){


       
        String company = q.Opportunity.Owner.SubCompany__c;
        String accId =  q.Opportunity.AccountId ;
        String appAccId = q.ApplicableCustomers__c; 
        String parentId = q.Opportunity.Account.ParentId ;
        String  salescode = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(company);

          
        List<QuoteProduct__c> qpList = [select Id,OriginalPrice__c,Product__c ,Product__r.Name,Product__r.Brand__c,Product__r.Model__c,Product__r.ProductName__c,
                Product__r.Category1__c,Product__r.Category2__c,Product__r.Category0__c,Product__r.zl__c,Product__r.TypeName__c,
                Product__r.NCCode__c,Product__r.SerialNo__c,Product__r.Spec__c ,SalesPrice__c ,GPOPrice__c ,Product__r.swjhdj__c,Product__r.GroupSubCompanyPrice__c,
                Product__r.GroupDeclarationDealerPrice__c,Product__r.GroupRegionalDistributorsPrice__c,Product__r.GroupTerminalGuidePric__c 
             from QuoteProduct__c where Quote__c =:prId ];

        List<ProductBean> tmp = new List<ProductBean>();

         if(qpList == null || qpList.size() == 0)return tmp ;

         Set<Id>  pset= new Set<Id>();
         System.debug('***'+qpList);
        Set<Id> maccuras = new Set<Id>();
        for(QuoteProduct__c  qp : qpList){
            pset.add(qp.Product__c);
            if(MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c))maccuras.add(qp.Product__c);
        }
        Map<Id,Price__c> maccuraPrMap = type != 'third'|| maccuras.isEmpty() ?new  Map<Id,Price__c>():   ImportObject.getPriceMap(maccuras, '迈克生物股份有限公司',false);
        Map<Id,Price__c> prMap =ImportObject.getPriceMap(pset, company,province);
                System.debug('AdjustPriceListController==>'+pset);
                System.debug('AdjustPriceListController==>'+company);
                System.debug('AdjustPriceListController==>'+province);
                System.debug('AdjustPriceListController==>'+prMap);

        Map<Id,AveragePrice__c> lastprMap  = ImportObject.getLastMothPrice(pset,company,province);

        System.debug('getProductFromQuoteBean==>'+ appAccId + ' '+ accId);

        Map<Id,PriceList__c> priceListMap = ImportObject.getPriceListMap(pset, accId,appAccId, salescode,company,false);
        Map<Id,PriceList__c> sysPriceListMap = new Map<Id,PriceList__c>();

        if(parentId != null ) syspriceListMap =ImportObject.getPriceListMap(pset, parentId, salescode,company,true);
        for(QuoteProduct__c qp :qpList){
            tmp.add(new ProductBean(qp, maccuraPrMap.containsKey(qp.Product__c) ? maccuraPrMap.get(qp.Product__c) :  prMap.get(qp.Product__c),lastprMap.get(qp.Product__c),priceListMap.get(qp.Product__c),sysPriceListMap.get(qp.Product__c),rightMap,type == 'third'));
        }

        return tmp;

    }
    public class ProductBean{
    	public String name ;//产品名称
    	public String serialno;//货号
    	public String brand ;//品牌
        public String model ;//型号 
    	public String spec;//规格
        public String cate1 ;//一级分类

    	public Decimal price ;//本次报价
    	public Decimal orlprice; //原供货价审批参考
        public Decimal marketPrice;//市场报价审批参考
    	public Decimal terprice ;//终端指导价审批参考
    	public Decimal lastprice ;//上月平均价审批参考
    	public Decimal subprice ;//子公司成本审批参考

    	public Decimal invoiceprice ;//报单经销商价审批参考
    	public Decimal areaprice ;//区域经销商价审批参考

    	public Decimal thirdprice;//第三方价格
        public String  type ; //调价 还是 新增  
        public String reason ;
        public Decimal gpoprice;//gpo价格

        public Decimal group1price;// GroupRegionalDistributorsPrice__c //集团一级经销商价
        public Decimal group2price;//GroupDeclarationDealerPrice__c //集团二级经销商价
        public Decimal groupTprice;//GroupTerminalGuidePrice__c //集团终端指导价 

        public Decimal groupsubcompanyprice;

     /* 
        2020-03-25
        1、查看明细PDF新增集团一级经销商价、集团二级经销商价、集团终端指导价的对比
        2、经销商客户展示集团一级经销商价、集团二级经销商价，终端客户展示终端指导价，以上字段权限开通给集团产品经理、集团项目经理、集团产品总监、系统管理员
     */

    	public ProductBean (AdjustPriceProduct__c ap,Price__c pr,Map<String,Boolean> rightMap , Boolean isThird  ){
             if(pr == null ) pr = new Price__c();
    		name =ap.Product__r.ProductName__c == null ?  ap.Product__r.Name :ap.Product__r.ProductName__c;
    		serialno = ap.Product__r.SerialNo__c;
    		brand = ap.Product__r.Brand__c;
    		spec = ap.Product__r.Spec__c;
            cate1 = ap.Product__r.Category1__c;
            model = ap.Product__r.Model__c;


    		price = ap.AdjustSalesPrice__c;
    		orlprice = ap.OriginalPrice__c;

    		terprice = ap.HospitalManagerPrice__c;

       		lastprice = ap.LastMonthAveragePrice__c;
    		subprice = ap.InstCost__c ;
    		invoiceprice = ap.InvoiceDealerPrice__c;
    		areaprice = ap.AreaDealerPrice__c;
            if( rightMap.get('GroupSubCompanyPrice__c') ==true  ) groupsubcompanyprice = ap.Product__r.GroupSubCompanyPrice__c;

    		if( rightMap.get('ThirdPrice')  == true )thirdprice = ap.SystemPrice__c;
            if(rightMap.get('GPOPrice__c')  == true )gpoprice = ap.GPOPrice__c;

            type = orlprice == null ? '新增价格' : '调整价格';
            reason = ap.QuotoReason__c;
            marketPrice = isThird  &&  MaccuraBrandUtil.maccura.contains(brand) ? ap.Product__r.GroupMarketPrice__c :  pr.MarketPrice__c;
                
            
            if(rightMap.get('GroupTerminalGuidePric__c')  == true)groupTprice = ap.Product__r.GroupTerminalGuidePric__c;//.GroupTerminalGuidePrice__c;
            if(rightMap.get('GroupRegionalDistributorsPrice__c')  == true)group1price = ap.Product__r.GroupRegionalDistributorsPrice__c;//;pr.GroupRegionalDistributorsPrice__c;
            if(rightMap.get('GroupDeclarationDealerPrice__c')  == true)group2price = ap.Product__r.GroupDeclarationDealerPrice__c;//pr.GroupDeclarationDealerPrice__c;
          
        

    	}
        public ProductBean (QuoteProduct__c ap,Price__c pr,AveragePrice__c av ,PriceList__c pl ,PriceList__c syspl,Map<String,Boolean> rightMap,Boolean isThird ){

            if(pr == null ) pr = new Price__c();
            name =ap.Product__r.ProductName__c;

            serialno = ap.Product__r.SerialNo__c;
            brand = ap.Product__r.Brand__c;
            spec = ap.Product__r.Spec__c;
            cate1 = ap.Product__r.Category1__c;

            model = ap.Product__r.Model__c;

            if( rightMap.get('GroupSubCompanyPrice__c')==true )groupsubcompanyprice = ap.Product__r.GroupSubCompanyPrice__c;

            price = ap.SalesPrice__c;
            orlprice = ap.OriginalPrice__c;
            if(rightMap.containsKey('GPOPrice__c'))gpoprice = ap.GPOPrice__c;
            type = orlprice == null ? '新增价格' : '调整价格';
           

            if(rightMap.get('HospitalManagerPrice__c')  == true) terprice =isThird  &&  MaccuraBrandUtil.maccura.contains(brand) ? ap.Product__r.GroupTerminalGuidePric__c :   pr.HospitalManagerPrice__c; 
            if(rightMap.get('InstCost__c')  == true) subprice =  pr.InstCost__c ;

             marketPrice = isThird  &&  MaccuraBrandUtil.maccura.contains(brand) ? ap.Product__r.GroupMarketPrice__c :  pr.MarketPrice__c;

            if(rightMap.get('InvoiceDealerPrice__c')  == true)invoiceprice = isThird  &&  MaccuraBrandUtil.maccura.contains(brand) ? ap.Product__r.GroupDeclarationDealerPrice__c :  pr.InvoiceDealerPrice__c;
            if(rightMap.get('AreaDealerPrice__c')  == true)areaprice = isThird  &&  MaccuraBrandUtil.maccura.contains(brand) ? ap.Product__r.GroupRegionalDistributorsPrice__c :  pr.AreaDealerPrice__c;
        

                // if(rightMap.get('GroupTerminalGuidePrice__c')  == true)groupTprice = pr.GroupTerminalGuidePrice__c;
                // if(rightMap.get('GroupRegionalDistributorsPrice__c')  == true)group1price = pr.GroupRegionalDistributorsPrice__c;
                // if(rightMap.get('GroupDeclarationDealerPrice__c')  == true)group2price = pr.GroupDeclarationDealerPrice__c;

            
            if(rightMap.get('GroupTerminalGuidePric__c')  == true)groupTprice = ap.Product__r.GroupTerminalGuidePric__c;//.GroupTerminalGuidePrice__c;
            if(rightMap.get('GroupRegionalDistributorsPrice__c')  == true)group1price = ap.Product__r.GroupRegionalDistributorsPrice__c;//;pr.GroupRegionalDistributorsPrice__c;
            if(rightMap.get('GroupDeclarationDealerPrice__c')  == true)group2price = ap.Product__r.GroupDeclarationDealerPrice__c;//pr.GroupDeclarationDealerPrice__c;
          
        
            if(pl != null ) orlprice = pl.Price__c; 
            if(syspl != null && rightMap.get('GPOPrice__c')  == true )thirdprice =  syspl.Price__c ;
            if(av != null ) lastprice = av.AveragePrice__c;
            type = orlprice == null ? '新增价格' : '调整价格';


        }




    }
}